const express = require("express");
const fs = require('fs');
const path = require('path');
/* formidable用于解析表单数据，特别是文件上传 */
const formidable = require('formidable');
/* 用于时间格式化 */
const formatTime = require('silly-datetime');
const uuid = require('node-uuid'); // 生成id
const {NewsModel} = require("../models/news");
const newsService = require("../services/news");

let router = express.Router();

//上传图片
router.post('/upload/single', (req, res) => {

  /* 创建上传表单 */
  let form = new formidable.IncomingForm();
  /* 设置编码格式 */
  form.encoding = 'utf-8';
  /* 设置上传目录(这个目录必须先创建好) */
  form.uploadDir = path.join(__dirname, '../serverImage');
  /* 保留文件后缀名 */
  form.keepExtensions = true;
  /* 设置文件大小 */
  form.maxFieldsSize = 2 * 1024 *1024;

  /* 格式化form数据 */
  form.parse(req, (err, fields, files) => {
    let file = files.file;
    /* 如果出错，则拦截 */
    if(err) {
      return res.send({'code': 500, msg: '服务器内部错误', data: ''});
    }

    if(file.size > form.maxFieldsSize) {
      fs.unlink(file.path);
      return res.send({'code': -1, 'msg': '图片不能超过2M', data: ''});
    }

    /* 存储后缀名 */
    let extName = '';

    switch (file.type) {
      case 'image/png':
        extName = 'png';
        break;
      case 'image/x-png':
        extName = 'png';
        break;
      case 'image/jpg':
        extName = 'jpg';
        break;
      case 'image/jpeg':
        extName = 'jpg';
        break;
    }
    if(extName.length == 0) {
      return res.send({'code': -1, 'msg': '只支持jpg和png格式图片', data: ''});
    }

    /* 拼接新的文件名 */
    let time = formatTime.format(new Date(), 'YYYYMMDDHHmmss');
    let num = Math.floor(Math.random() * 8999 + 10000);
    let imageName = `${time}_${num}.${extName}`;
    let newPath = form.uploadDir + '/' + imageName;

    /* 更改名字和路径 */
    fs.rename(file.path, newPath, (err) => {
      if(err) {
        return res.send({'code': -1, 'msg': '图片上传失败', data: ''});
      } else {
        return res.send({'code': 200, 'msg': '图片上传成功', data: {url: `http://localhost:5000/serverImage/${imageName}`}});
      }
    })
  })
});

// 新增修改 保存新闻
router.post('/save', async (req, res, next) => {

  try {
    let {news_id, news_title, news_source, news_type, news_detail, news_img }= req.body;
    if (news_id === '') {
      // 新增
      news_id = uuid.v1();
    }
    await NewsModel.create({
      news_id: news_id,
      news_title: news_title,
      news_source: news_source,
      news_type: news_type,
      news_detail: news_detail,
      news_img: news_img
    }).then(function(result) {
      res.send({ code: 200, msg: "保存成功", data: "" });
    }).catch(function(error)  {
      res.send({ code: -1, msg: "保存失败", data: "" });
    });

  } catch(e) {
    next(e);
  }

});

// 获取新闻列表
router.post('/getNewsList', async (req, res, next) => {
  try {
    const {page, pageSize, news_type} = req.body;
    const result = await newsService.getNewsList(page, pageSize, news_type);
    const total = await NewsModel.count();
    const data = {data: result, total: total};
    res.send({code: 200, msg: "请求成功", data: data});
  } catch(e) {
    next(e);
  }
});

// 删除新闻
router.post('/deleteNews', async (req, res, next) => {
  try {
    const {news_id} = req.body;
    await newsService.deleteNews(news_id).then(function (result) {
      res.send({code: 200, msg: "删除成功", data: ""});

    }).catch(function (error) {
      res.send({code: -1, msg: "删除失败", data: ""});

    });

  } catch(e) {
    next(e);
  }
});

module.exports = router;